package com.aabte.lota.auth.auth.shiro;

import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.List;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/4/6
 */
public class CustomerModularRealmAuthorizer extends ModularRealmAuthorizer {

  private List<Realm> getSupportRealms(AuthenticationToken token) {
    List<Realm> supportRealms = Lists.newLinkedList();
    Collection<Realm> realms = getRealms();
    for (Realm realm : realms) {
      if (realm.supports(token)) {
        supportRealms.add(realm);
      }
    }
    return supportRealms;
  }

  @Override
  public boolean isPermitted(PrincipalCollection principals, String permission) {
    assertRealmsConfigured();

    Object primaryPrincipal = principals.getPrimaryPrincipal();
    List<Realm> supportRealms = getSupportRealms((AuthenticationToken) primaryPrincipal);

    for (Realm realm : supportRealms) {
      if (!(realm instanceof Authorizer)) {
        continue;
      }
      if (((Authorizer) realm).isPermitted(principals, permission)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public boolean isPermitted(PrincipalCollection principals, Permission permission) {
    assertRealmsConfigured();

    Object primaryPrincipal = principals.getPrimaryPrincipal();
    List<Realm> supportRealms = getSupportRealms((AuthenticationToken) primaryPrincipal);

    for (Realm realm : supportRealms) {
      if (!(realm instanceof Authorizer)) {
        continue;
      }
      if (((Authorizer) realm).isPermitted(principals, permission)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public boolean hasRole(PrincipalCollection principals, String roleIdentifier) {
    assertRealmsConfigured();

    Object primaryPrincipal = principals.getPrimaryPrincipal();
    List<Realm> supportRealms = getSupportRealms((AuthenticationToken) primaryPrincipal);

    for (Realm realm : supportRealms) {
      if (!(realm instanceof Authorizer)) {
        continue;
      }
      if (((Authorizer) realm).hasRole(principals, roleIdentifier)) {
        return true;
      }
    }
    return false;
  }
}
